package com.sinaapp.gavinzhang.GSpider.http;

import com.sinaapp.gavinzhang.GSpider.http.annotation.ServletClass;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.sinaapp.gavinzhang.GSpider.http.Tools.IsBase;

/**
 * Created by Gavin on 2015-11-22.
 */
public class ServletHandler {

    public boolean handle(HttpServletRequest request,HttpServletResponse response,Object object)
    {
        ServletClass servletClass = object.getClass().getAnnotation(ServletClass.class);
        String methodString = servletClass.function();
        Method method = null;
        for (Method m : object.getClass().getMethods())
        {
            System.out.println(m.getName());
            if (m.getName().equals(methodString))
            {
                method = m;
                break;
            }
        }
        if (method == null)
        {
            return false;
        }
        List<Class<?>> list = null;
        List<Object> variables = null;
        if (method.getParameterTypes().length != 0)
        {
            list = Arrays.asList(method.getParameterTypes());
            variables = new ArrayList<>();
            for (Class<?> c : list)
            {
                System.out.println(c.getName());
                System.out.println(request.getClass().getName());
                if (IsBase(request.getClass(), c)) {
                    variables.add(request);
                }else if (IsBase(response.getClass(), c)) {
                    variables.add(response);
                }
            }
        }

        if (variables != null)
        {
            try {
                method.invoke(object,variables.toArray());
                return true;
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }else {
            try {
                method.invoke(object);
                return true;
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static void main(String[] args)
    {
        /*ServletHandler servletHandler = new ServletHandler();
        servletHandler.handle(null,null,new SearchServlet());
        */
    }
}
